// pages/selectAddress/selectAddress.js
const addressService = require('../../service/addressService.js')
var amapFile = require('../../lib/amap-wx.js');
const utils = require('../../utils/util.js');
var QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
var demo = new QQMapWX({
  key: '3UJBZ-JK6W5-HHLIQ-QOF7B-CQ4U7-D3FJZ' // 必填
});
// load promise 
require('../../utils/wx-pro.js');

var markersData = {

  latitude: '',//纬度

  longitude: '',//经度

  key: "90c8f19695c4f355136cf3fb2e61c023"//你申请的高德地图key

};

Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectTabe: 1,
    adcode: "",
    formatted_address: "",
    shopAddressList: [],
    userAddressList: [],
    selectShopId: '',
    selectAddressId: '',
    IS_EXPRESS: 'false',
    showToast: false,
    toastMsg: ''
  },

  //错误提示
  showToastFuc(msg) {
    this.setData({
      showToast: true,
      toastMsg: msg
    })
    setTimeout(() => {
      this.setData({
        showToast: false,
        toastMsg: ''
      })
    }, 2000)
  },

  changeType: function (e) {
    this.setData({
      selectTabe: e.target.dataset.num
    })
    this.onShow()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    if (wx.getStorageSync('IS_EXPRESS') == 'true' && wx.getStorageSync('selectShopInfo')){
      this.setData({
        selectTabe: 0,
        IS_EXPRESS: 'true',
        selectAddressId: JSON.parse(wx.getStorageSync('selectAddressInfo')).addressId
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (!wx.getStorageSync('selectShopInfo')){
      this.location()
    }else{
      var data = JSON.parse(wx.getStorageSync('selectShopInfo'))
      if (wx.getStorageSync('IS_EXPRESS') == 'true') {
        var addressData = JSON.parse(wx.getStorageSync('selectAddressInfo'))
        that.setData({
          formatted_address: addressData.detailAddress,
          selectShopId: data.id
        })
        markersData.latitude = addressData.latitude,
        markersData.longitude = addressData.longitude
      }else{
        that.setData({
          formatted_address: data.shopAddress,
          selectShopId: data.id
        })
      }
      if (that.data.selectTabe == 0) {
        that.getUserAddressList()
      } else if (that.data.selectTabe == 1) {
        if (wx.getStorageSync('IS_EXPRESS') == 'true') {
          var addressData = JSON.parse(wx.getStorageSync('selectAddressInfo'))
          markersData.latitude = addressData.latitude,
          markersData.longitude = addressData.longitude
        } else {
          that.setData({
            IS_EXPRESS: 'false',
            selectShopId: JSON.parse(wx.getStorageSync('selectShopInfo')).id
          })
          markersData.latitude = data.desLatitude,
          markersData.longitude = data.desLongitude
        }
        that.getShopList()
      }
    }
  },
  location: function() {
    var that = this;
    //用微信小程序的api接口获取经度，维度
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        markersData.latitude = res.latitude,
        markersData.longitude = res.longitude
        var myAmapFun = new amapFile.AMapWX({ key: markersData.key });
        myAmapFun.getRegeo({
          location: '' + markersData.longitude + ',' + markersData.latitude + '',//location的格式为'经度,纬度'
          success: function (data) {
            //成功回调
            that.setData({
              adcode: data[0].regeocodeData.addressComponent.adcode,
              formatted_address: data[0].regeocodeData.formatted_address
            })
            if (that.data.selectTabe == 0) {
              that.getUserAddressList()
            } else if (that.data.selectTabe == 1) {
              that.getShopList()
            }
          },
          fail: function (info) {
            //失败回调
            console.log(info)
          }
        })
      },
      // 这里是点击拒绝触发的方法  
      fail: function (res2) {
        // 在这里做一下兼容，有些同行业的用户会点击拒绝玩一玩看你们的小程序是否存在bug，  
        // 所以在这里还是加上下面这两行代码吧，打开微信小程序的设置，允许小程序重新授权的页面  
        wx.openSetting({
          success: (res) => {
            // 下面的代码格式按照我的写，不要看工具打印的什么，在这里提醒大家一句，有时候不能相信开发者工具，因为  
            // android和ios还有工具底层的js库是不同的，有些时候坑的你是一点脾气也没有，所以大家注意一下，  
            // 不相信的慢慢的去自己跳坑吧  
            if (res.authSetting["scope.location"]) {
              // 进入这里说明用户重新授权了，重新执行获取用户信息的方法  
              that.location()
            }
          }
        })
      }
    })
  },
  backOne(){
    wx.navigateBack()
  },
  locationBtn: function() {
    this.location()
  },
  getShopList: function () {
    var params = {
      longitude: markersData.longitude,
      latitude: markersData.latitude
    }
    addressService.getShopAddressList(params).then(data => {
      if (data.code == 200) {
        this.setData({
          shopAddressList: data.response.listSortShops
        })
      } else {
        this.showToastFuc(data.message)
      }
    })
    .catch(() => {
      console.log('error')
    })
  },
  getUserAddressList: function(){
    addressService.getUserAddressList().then(data => {
      if (data.code == 200) {
        this.setData({
          userAddressList: data.response.xcxAddressList
        })
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch(() => {
        console.log('error')
      })
  },

  showMap(event){
    console.log(event.currentTarget.dataset.info)
    var data = event.currentTarget.dataset.info
    var latitude = data.desLatitude
    var longitude = data.desLongitude
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale: 28,
      name: data.name,
      address: data.shopAddress
    })
  },

  selectShop(event){
    console.log(event.currentTarget.dataset.info)
    var data = event.currentTarget.dataset.info
    wx.setStorageSync('IS_EXPRESS', 'false')
    wx.setStorageSync('selectShopInfo', JSON.stringify(data))
    wx.navigateBack({
      delta: 6
    })
  },

  selectUserAddress(event){
    var _this = this
    console.log(event.currentTarget.dataset.info)
    var dataMore = event.currentTarget.dataset.info
    var params = {
      longitude: dataMore.longitude,
      latitude: dataMore.latitude
    }
    addressService.getNearestShop(params).then(data => {
      if (data.code == 200) {
        console.log(data.response.nearShop)
        if (!data.response.nearShop){
          wx.showModal({
            title: '提示',
            content: '您选择的地址不在我们门店的配送范围内，请尝试选择其它地址呦！',
            confirmText: '门店自提',
            cancelText: '重新选择',
            success: function (res) {
              if (res.confirm) {
                _this.setData({
                  selectTabe: 1
                })
                _this.getShopList()
              } else if (res.cancel) {
                console.log('用户点击了重新选择')
              }
            }
          })
        }else{
          wx.setStorageSync('IS_EXPRESS', 'true')
          wx.setStorageSync('selectAddressInfo', JSON.stringify(dataMore))
          var dataList = data.response.nearShop
          wx.setStorageSync('selectShopInfo', JSON.stringify(dataList))
          console.log("have shop!")
          wx.navigateBack({
            delta: 6
          })
        }
      } else {
        this.showToastFuc(data.message)
      }
    })
      .catch(() => {
        console.log('error')
      })
  },

  addressLink(){
    var that = this
    wx.chooseAddress({
      success: function (res) {
        console.log(res)
        that.map(res)
      }
    })
  },

  map: function (data) {
    var that = this;
    demo.geocoder({
      address: data.provinceName + data.cityName + data.countyName + data.detailInfo,
      success: function (res) {
        var params = {
          provinceId: data.nationalCode.substr(0, 2) + '0000',
          cityId: data.nationalCode.substr(0, 4) + '00',
          districtId: data.nationalCode,
          detailAddress: data.provinceName + data.cityName + data.countyName + data.detailInfo,
          longitude: res.result.location.lng,
          latitude: res.result.location.lat,
          contactName: data.userName,
          contactPhone: data.telNumber
        }
        addressService.saveXcxAddress(params).then(data => {
          if (data.code == 200) {
            console.log('已保存')
          } else {
            this.showToastFuc(data.message)
          }
        })
          .catch(() => {
            console.log('error')
          })
      },
      fail: function (res) {
        console.log(res);
      }
    })
  }
  
})